<?php
namespace addons\yexam\service;


use app\admin\model\yexam\Answer;
use app\admin\model\yexam\Fav;
use app\admin\model\yexam\Question;
use app\admin\model\yexam\QuestionLog;
use think\Exception;

class Unit
{

    public $model;

    public function __construct()
    {
        $this->model = new \app\admin\model\yexam\Unit();
    }

    /**
     * 获取上次答题定位num
     */
    public function getLastPosition($unit_id,$user_id){

        //获取当前单元已经练习的最后的题目ID
        $logModel = new QuestionLog();
        $data = $logModel
            ->field("a.question_id")
            ->alias("a")
            ->join("yexam_question b","a.question_id=b.id",'inner')
            ->where(['a.unit_id'=>$unit_id,'user_id'=>$user_id])->order('a.lasttime desc')->find();
        if(empty($data)){
            return 1;
        }else{
            $questionModel = new \app\admin\model\yexam\Question();
            $questionList = $questionModel->field("id")->where(['unit_id'=>$unit_id])->order("type asc,id asc")->select();
            $num = 1;
            foreach($questionList as $k=>$v){
                $num++;
                if($data['question_id'] == $v['id']){
                    break;
                }

            }
            if($num>count($questionList)){
                $num = 1;
            }
            return $num;
        }
    }


    /**
     * 递归获取下级终极章节ID
     * @param $id
     * @param $arr
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function _up_unit($id, &$arr)
    {
        $unitModel = new \app\admin\model\yexam\Unit();
        $list = $unitModel->where(['pid'=>$id])->select();
        foreach ($list as $k=>$v) {
            if ($v['is_last'] == 1) {
                $arr[] = $v['id'];
            } else {
                $this->_up_unit($v['id'], $arr);
            }
        }
        return $arr;
    }


    /**
     * 获取指定章节下的章节练习的题目正确数量
     * @throws Exception
     */
    public function getUnitQuestionRightNum($unit_id,$user_id){
        $unit_ids = [$unit_id];
        try {
            self::_up_unit($unit_id, $unit_ids);
        } catch (Exception $e) {

        }

        $questionModel = new Question();
        return $questionModel
            ->alias("question")
            ->join("yexam_question_log log","question.id=log.question_id","inner")
            ->where(['question.unit_id'=>['in',$unit_ids],"log.state"=>1,"log.user_id"=>$user_id])->count();
    }

    /**
     * 获取指定章节下的章节练习的题目练习数量
     * @throws Exception
     */
    public function getUnitQuestionTestNum($unit_id,$user_id){
        $unit_ids = [$unit_id];
        try {
            self::_up_unit($unit_id, $unit_ids);
        } catch (Exception $e) {

        }

        $questionModel = new Question();
        return $questionModel
            ->alias("question")
            ->join("yexam_question_log log","question.id=log.question_id","inner")
            ->where(['question.unit_id'=>['in',$unit_ids],"log.user_id"=>$user_id])->count();
    }

    /**
     * 获取指定章节下的章节练习的题目数量
     * @throws Exception
     */
    public function getUnitQuestionNum($unit_id){
        $unit_ids = [$unit_id];
        try {
            self::_up_unit($unit_id, $unit_ids);
        } catch (Exception $e) {

        }

        $questionModel = new Question();
        return $questionModel->where(['unit_id'=>['in',$unit_ids]])->count();
    }

    /**
     * 获取章节正确率
     * @throws Exception
     */
    public function right_scale($unit_id,$user_id){
        //获取正确数量
        $test_num = self::getUnitQuestionTestNum($unit_id,$user_id);
        $right_num = self::getUnitQuestionRightNum($unit_id,$user_id);

        return empty($test_num)?0:intval(bcdiv($right_num,$test_num,2)*100);
    }

    /**
     * 章节练习答题
     */
    public function doanswer($id,$answer,$user_id){

        $questionModel = new \app\admin\model\yexam\Question();
        if($questionInfo = $questionModel->where(['id'=>$id])->find()){
            if (preg_replace('# #', '', $questionInfo['right_answer']) != preg_replace('# #', '', $answer)) {
                $result = 0;
            }else{
                $result = 1;
            }
        }else{
            return;
        }

        //写入答题记录
        $logModel = new QuestionLog();
        if($log = $logModel->where(['question_id'=>$id,'user_id'=>$user_id])->find()){
            $log->save(['lasttime'=>time(),'state'=>$result]);
            $log->setInc('total_num');
            if(empty($result)){
                $log->setInc('error_num');
            }else{
                $log->save(['error_num'=>0]);
            }
        }else{
            $logModel = new QuestionLog();
            $logModel->save([
                'subject_id'=>$questionInfo['subject_id'],
                'unit_id'=>$questionInfo['unit_id'],
                'question_id'=>$id,
                'user_id'=>$user_id,
                'createtime'=>time(),
                'lasttime'=>time(),
                'state'=>$result
            ]);
        }

        return $result;
    }

    /**
     * 获取章节练习错题列表
     */
    public function getErrorLogList($subject_id,$user_id,$page,$limit){
        $logModel = new QuestionLog();
        $count = $logModel
            ->alias("log")
            ->join("yexam_unit unit","log.unit_id=unit.id",'inner')
            ->where(['log.subject_id'=>$subject_id,'log.user_id'=>$user_id,'log.state'=>0])->group("unit.id")->count();
        if($page){
            $data = $logModel
                ->alias("log")
                ->field("unit.id,unit.unit_name,count(log.id) as error_num")
                ->join("yexam_unit unit","log.unit_id=unit.id",'inner')
                ->where(['log.subject_id'=>$subject_id,'log.user_id'=>$user_id,'log.state'=>0])
                ->page($page,$limit)
                ->group("unit.id")
                ->select();
        }else{
            $data = $logModel
                ->alias("log")
                ->field("unit.id,unit.unit_name,count(log.id) as error_num")
                ->join("yexam_unit unit","log.unit_id=unit.id",'inner')
                ->where(['log.subject_id'=>$subject_id,'log.user_id'=>$user_id,'log.state'=>0])
                ->group("unit.id")
                ->select();
        }


        return ['total'=>$count,'data'=>$data];
    }

    /**
     * 获取章节练习错题答题卡
     */
    public function  getErrorCard($unit_id,$user_id){
        $logModel = new QuestionLog();
        $data = collection($logModel
            ->alias("log")
            ->field("question.id")
            ->join("yexam_question question","log.question_id=question.id",'inner')
            ->join("yexam_unit unit","log.unit_id=unit.id",'inner')
            ->where(['log.unit_id'=>$unit_id,'log.user_id'=>$user_id,'log.state'=>0])
            ->order("question.type asc,question.id asc")
            ->select());

        return $data;
    }

    /**
     * 移除章节考试错题
     * @param $unit_id
     * @param $id
     * @param $user_id
     */
    public function removeErrorQuestion($id,$user_id){
        $logModel = new QuestionLog();
        $row = $logModel
            ->where(['unit_id'=>['neq',0],'user_id'=>$user_id,'question_id'=>$id,'state'=>0])
            ->find();
        if(empty($row)){
            return true;
        }
        $row->delete();
        return true;
    }



    /**
     * 获取章节练习错题答题卡
     */
    public function  getFavCard($unit_id,$user_id){
        $favModel = new Fav();
        $data = collection($favModel
            ->alias("fav")
            ->field("question.id")
            ->join("yexam_question question","fav.question_id=question.id",'inner')
            ->join("yexam_unit unit","fav.unit_id=unit.id",'inner')
            ->where(['fav.unit_id'=>$unit_id,'fav.user_id'=>$user_id])
            ->order("question.type asc,question.id asc")
            ->select());

        return $data;
    }

    /**
     * 获取父级章节名称集合
     */
    public function getParentNames($unit_id,&$arr){
        $unitModel = new \app\admin\model\yexam\Unit();
        $unitInfo = $unitModel->where(['id'=>$unit_id])->find();
        if($unitInfo){
            $parent = $unitModel->where(['id'=>$unitInfo['pid']])->find();
            if($parent){
                $arr[] = $parent['unit_name'];

                if(!empty($parent['pid'])){
                    $this->getParentNames($parent['pid'], $arr);
                }
            }
        }

        return $arr;
    }

    /**
     * 获取章节练习收藏列表
     */
    public function getFavList($subject_id,$user_id,$page,$limit){
        $favModel = new Fav();
        $count = $favModel
            ->alias("fav")
            ->join("yexam_unit unit","fav.unit_id=unit.id",'inner')
            ->where(['unit.subject_id'=>$subject_id,'fav.user_id'=>$user_id])
            ->count();

        if($page){
            $data = $favModel
                ->alias("fav")
                ->field("unit.id,unit.unit_name,count(fav.id) as num")
                ->join("yexam_unit unit","fav.unit_id=unit.id",'inner')
                ->where(['unit.subject_id'=>$subject_id,'fav.user_id'=>$user_id])
                ->group("unit.id")
                ->page($page,$limit)
                ->select();
        }else{
            $data = $favModel
                ->alias("fav")
                ->field("unit.id,unit.unit_name,count(fav.id) as num")
                ->join("yexam_unit unit","fav.unit_id=unit.id",'inner')
                ->where(['unit.subject_id'=>$subject_id,'fav.user_id'=>$user_id])
                ->group("unit.id")
                ->select();
        }

        return ['total'=>$count,'data'=>$data];
    }


}